<?php
/**
 * XuYuan Project
 *
 * @package	XueYuan 
 * @author	Jiuchi Team
 * @since	Version 1.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * User controller class
 * @author Wayne Yu
 */
class Comment extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->library('session');
		$this->load->library('apioutput');
		$this->load->library('msgblock');
		$this->load->helper('url');
		$uid = $this->session->userdata('uid');
		if(empty($uid)){
			redirect(site_url('login'));
		}
		$this->load->model('user_model');
		$this->load->model('user_dynamic_model');
		$this->load->model('circle_model');
		$this->load->model('circle_category_model');
		$this->load->model('circle_user_model');
		$this->load->model('circle_admin_model');
		$this->load->model('topic_model');
		$this->load->model('comment_model');
		$this->load->model('reply_model');
	}
	
	/**
	 * Create page
	 */
	public function create(){
		$circleCategory = $this->circle_category_model->retrieve();
		$data = array(
				'cirCate'	=>	$circleCategory
		);
		$this->load->view('circle/createCircle', $data);
	}
	
	/**
	 * create circle post
	 */
	public function createPost($tid){
		$input = $this->input->post();
		if(empty($input['content'])){
			die("<script>alert('非法请求，请联系管理员！');window.history.back();</script>");
		}
	
		$topicInfo = $this->topic_model->getInfo($tid);
		$circleInfo = $this->circle_model->getInfo($topicInfo['circle_id']);
		if(!$this->circle_user_model->checkIsMember($this->session->userdata('uid'), $topicInfo['circle_id'])){
			die("<script>alert('您尚未加入该圈子，请先申请加入！');window.history.back();</script>");
		}
		$topic_img = $this->getPostImg($tid);
		$data = array(
				'topic_id'				=>	$tid,
				'user_id'				=>	$this->session->userdata('uid'),
				'comments_img'			=>	$topic_img,
				'content'				=>	$input['content']
		);

		//save
		$this->comment_model->begin();
		$tid = $this->comment_model->createEntity($data);
		if($tid <= 0){
			die("<script>alert('创建失败，请稍后重试！');window.history.back();</script>");
		}
		$data = array(
				'user_id'		=> $this->session->userdata('uid'),
				'title'			=> $topicInfo['title'],
				'obj_id'		=> $tid,
				'type'			=> 2,
				'content'		=> $input['content'],
				'content_img'	=> $topic_img,
				'circle_id'		=> $circleInfo['id'],
				'circle_name'	=> $circleInfo['name'],
		);
		$this->user_dynamic_model->createEntity($data);
		if($tid <= 0){
			$this->comment_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.history.back();</script>");
		}
		
		$res = $this->topic_model->updateInfo($tid,array('comments_number' => ($topicInfo['comments_number']+1)));
		if($res){
			$this->comment_model->rollback();
			die("<script>alert('创建失败，请稍后重试！');window.history.back();</script>");
		}
		$this->comment_model->commit();
		
		die("<script>alert('评论发表成功！');window.history.back();</script>");
	}
	
	private function getPostImg($tid){
		if(empty($_FILES['filename'])){
			return '';
		}
		$nameExten = explode('.', $_FILES['filename']['name']);
		$type = end($nameExten);
		if(!in_array($_FILES['filename']['type'], array('image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/png'))){
			$this->msgblock->addError('图片格式不正确！');
			return '';
		}
		if($_FILES['filename']['size'] > 5*1024*1024){
			$this->msgblock->addError('图片过大!');
			return '';
		}
			
		$path = dirname(BASEPATH).'/uploads/comments/'.$tid;
		if(!is_dir($path)){
			if(false == mkdir($path)){
				$this->msgblock->addError('没有权限，请联系管理员！');
				return '';
			}
		}
		$filepath= $path.'/'.$_FILES['filename']['name'];
			
		if(is_uploaded_file($_FILES['filename']['tmp_name'])){
			if(move_uploaded_file($_FILES['filename']['tmp_name'], $filepath)){
				return '/uploads/topic/'.$cid.'/'.$_FILES['filename']['name'];
			} else{
				$this->msgblock->addError('没有权限，请联系管理员！');
				return '';
			}
		} else{
			$this->msgblock->addError('没有权限，请联系管理员！');
			return '';
		}
	}
	
	public function view($comment_id){
		$commentInfo = $this->comment_model->getInfo($comment_id);
		$userInfo = $this->user_model->getInfo($commentInfo['user_id']);
		$data = array(
				'commentInfo'	=>	$commentInfo,
				'userInfo'	=>	$userInfo
		);
		$this->load->view('comments/view', $data);
	}
	
	/**
	 * get topics' comments
	 */
	public function getCommentReplies($cid){
		$input = $this->input->post();
		$pageSize = isset($input['amount'])?$input['amount']:5;
		$laseItem = isset($input['last'])?$input['last']:0;
		
		$data = $this->reply_model->getCommentReplies($cid, $pageSize, $laseItem);
		foreach ($data as $key => $val){
			$uInfo  = $this->user_model->getInfo($val['user_id']);
			$ruInfo  = $this->user_model->getInfo($val['reply_user_id']);
			$data[$key] = array(
					'headportrait'	=>	'<a href="'.site_url('user/view/'.$val['user_id']).'"><img style="width:40px;" src="'.(isset($uInfo['headportrait'])?$uInfo['headportrait']:'').'" class="img-avatar"></a>',
					'username'		=>	isset($uInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['user_id']).'">'.$uInfo['nickname'].'</a>':'',
					'replyname'		=>	isset($ruInfo['nickname'])?'<a href="'.site_url('user/view/'.$val['reply_user_id']).'">'.$ruInfo['nickname'].'</a>':'',
					'content'		=>	$val['content'],
					'reply_user_id'		=>	$uInfo['id'],
					'viewbutton'	=>	'<a href="'.site_url('comments/view/'.$val['id']).'">查看回复</a>'
			);
		}
		echo json_encode($data);
	}
	
	/**
	 * create circle post
	 */
	public function createReplyPost(){
		$input = $this->input->post();
		if(empty($input['comment_id'])|| empty($input['reply_user_id']) || empty($input['content'])){
			$this->apioutput->apiResponseError('非法请求，请稍后重试！');
		}
		$data = array(
				'user_id'				=>	$this->session->userdata('uid'),
				'comment_id'			=>	$input['comment_id'],
				'reply_user_id'			=>	$input['reply_user_id'],
				'content'				=>	$input['content'],
				'creator'				=>	$this->session->userdata('uid')
		);
	
		/**
		 * 检测是否在圈子里等
		 */
		$this->msgblock->addError('您尚未加入该圈,请先申请加入此圈！');
		$this->apioutput->apiResponseError('您尚未加入该圈,请先申请加入此圈！');
		
		//save
		$this->reply_model->begin();
		$cid = $this->reply_model->createEntity($data);
		if($cid <= 0){
			$this->apioutput->apiResponseError('创建失败，请稍后重试！');
		}
		/**
		 * 更新动态表
		 */
// 		$data = array(
// 				'circle_id' => $cid,
// 				'user_id'	=> $this->session->userdata('uid'),
// 				'is_primary'=> '1'
// 		);
// 		$res = $this->circle_admin_model->createEntity($data);
// 		if(!$res){
// 			$this->circle_model->rollback();
// 			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('circle/create')."';</script>");
// 		}
// 		$data = array(
// 				''
// 		);
// 		$res = $this->circle_user_model->createEntity($data);
// 		if(!$res){
// 			$this->circle_model->rollback();
// 			die("<script>alert('创建失败，请稍后重试！');window.location.href='".site_url('circle/create')."';</script>");
// 		}
	
		$this->reply_model->commit();
	
		$this->apioutput->apiResponseSuccess();
	}
}